package avicit.im.lantop.basic.libstructuredefine.action;

import avicit.cbb.appreg.service.CommSysInfoIntfsService;
import avicit.cbb.tabledefine.service.CommTableManagerIntfsService;
import avicit.cbb.tabledefine.service.api.CommTableManagerIntfsServiceApi;
import avicit.cbb.tabledefine.service.api.CommSysInfoIntfsServiceApi;
import avicit.im.lantop.archiveclassmanager.service.ArchiveClassManagerIntfsService;
import avicit.im.lantop.archiveclassmanager.service.api.ArchiveClassManagerIntfsServiceApi;
import avicit.im.lantop.basic.libstructuredefine.dao.LantopArchiveClassManagerDao;
import avicit.im.lantop.basic.libstructuredefine.dao.LantopArchiveClassManagerDaoApi;
import avicit.im.lantop.basic.libstructuredefine.dao.api.LantopArchiveClassManagerDaoApi;
import avicit.im.lantop.basic.libstructuredefine.domain.LantopArchiveClassT;
import avicit.im.lantop.basic.libstructuredefine.action.service.service.LantopArchiveClassService;
import avicit.im.lantop.basic.libstructuredefine.action.service.service.LantopArchiveClassService2;
import avicit.im.lantop.basic.libstructuredefine.action.service.api.LantopArchiveClassServiceApi;
import avicit.im.lantop.basic.libstructuredefine.service.api.LantopArchiveClassService2;
import avicit.im.lantop.basic.libstructuredefine.service.api.LantopArchiveClassService2Api;
import avicit.platform6.api.session.SessionHelper;
import avicit.platform6.api.syslog.dto.SysLog;
import avicit.platform6.api.syslookup.SysLookupAPI;
import avicit.platform6.api.syslookup.dto.SysLookupSimpleVo;
import avicit.platform6.api.syslookup.impl.SysLookupAPImpl;
import avicit.platform6.api.sysuser.SysOrgAPI;
import avicit.platform6.api.sysuser.dto.SysOrg;
import avicit.platform6.commons.utils.Pinyin4jUtil;
import avicit.platform6.commons.utils.RequestUtil;
import avicit.platform6.commons.utils.web.TreeNode;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.properties.PlatformConstant.OpResult;
import avicit.platform6.core.properties.PlatformConstant.OpType;
import avicit.platform6.core.spring.SpringFactory;
import avicit.platform6.modules.system.syslog.service.LogBaseFactory;
import avicit.platform6.modules.system.syslog.service.SysLogUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 金航数码科技有限责任公司
 * </p>
 * <p>
 * 作者： 刘中华
 * </p>
 * <p>
 * 邮箱：@avicit.com
 * </p>
 * <p>
 * 创建时间： 2014-10-8 上午11:55:28
 * </p>
 * <p>
 * 类说明：FIXME(库结构定义模板树Controller)
 * </p>
 * <p>
 * 修改记录：
 * </p>
 */
@Controller
@SuppressWarnings("deprecation")
@RequestMapping("/LantopArchiveClassController")
public class LantopArchiveClassController {

	private Logger logger = Logger.getLogger(this.getClass());

	@Resource
	LantopArchiveClassServiceApi lantopArchiveClassService;
	@Resource
	CommSysInfoIntfsService commSysInfoIntfsService;
	@Resource
	CommTableManagerIntfsServiceApi commTableManagerIntfsService;
	@Resource
	ArchiveClassManagerIntfsServiceApi archiveClassManagerIntfsService;
	@Autowired(required = true)
	LantopArchiveClassManagerDaoApi lantopArchiveClassManagerDao;

	SysLookupAPI upLoader = SpringFactory.getBean(SysLookupAPImpl.class);

	@Autowired
	private SysOrgAPI sysOrgAPI;

	@Resource
	LantopArchiveClassService2Api lantopArchiveClassService2;

	// 档案类型
	 Collection<SysLookupSimpleVo> lanTopArchiveTypeList =
	 upLoader.getLookUpListByType("LANTOP_ARCHIVE_TYPE");

	/**
	 * FIXME (前台展开时异步加载树)
	 *
	 * @author 刘中华
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/findChildsByNodeId")
	public Map<String,Object> findChildsByNodeId(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {

		Map<String,Object> map1 = new HashMap<>();

		List<TreeNode> nodes = new ArrayList<TreeNode>();
		try {
			int level = 1;
			// 默认为根节点
			if (StringUtils.isEmpty(id)) {
				String deptId = ThreadContextHelper.getDeptId();
				String orgId = ThreadContextHelper.getOrgId();
				int count = lantopArchiveClassService.getParentNodeByParentId(deptId,orgId);
				if (count == 0) {
					// 获取顶层节点
					lantopArchiveClassService.saveRootLantopArchiveTabClassVByType(deptId,orgId);
				}
				id = "ROOT";
			}

			// 第一次加载展开2层
			if ("ROOT".equals(id)) {
				level = 2;
			}

			nodes = this.lantopArchiveClassService.recurFindTreeNodesByParentId(id, level, ThreadContextHelper.getOrgId());
			if ("ROOT".equals(id)) {
				List<Map<String, Object>> publicFieldList = this.lantopArchiveClassService.getPublicFieldInfo();
				Map<String, Object> modelMap = new HashMap<String, Object>();
				Map<String, Object> FolderMap = new HashMap<String, Object>();
				for (int i = 0; i < publicFieldList.size(); i++) {
					Map<String, Object> map = publicFieldList.get(i);
					String archiveType = (String) map.get("ARCHIVE_TYPE");
					if ("-1".equals(archiveType)) {
						modelMap = map;
					} else {
						FolderMap = map;
					}
				}
				TreeNode model = new TreeNode();
				String ridModel = (String) modelMap.get("ID");
				String rnameModel = (String) modelMap.get("ARCHIVE_CLASS_NODE_NAME");
				String parentIdModel = (String) modelMap.get("PARENT_ID");
				model.setId(ridModel);
				model.setText(rnameModel);
				model.setAttributes(modelMap);
				model.set_parentId(parentIdModel);
				model.setIconCls("icon-im-newntable");
				TreeNode folder = new TreeNode();
				String rid = (String) FolderMap.get("ID");
				String rname = (String) FolderMap.get("ARCHIVE_CLASS_NODE_NAME");
				String parentId = (String) FolderMap.get("PARENT_ID");
				folder.setId(rid);
				folder.setText(rname);
				folder.setAttributes(FolderMap);
				folder.set_parentId(parentId);
				folder.setState("closed");
				folder.setIconCls("icon-im-newnmodulelib");
				folder.getChildren().add(model);
				nodes.get(0).getChildren().add(folder);
			}
			map1.put("flag", OpResult.success);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			map1.put("flag", OpResult.failure);
			map1.put("msg", "后台处理异常，" + e.getMessage());
		}
		map1.put("data", nodes);
		return map1;
	}

	/**
	 * FIXME (转向add页面的准备工作)
	 *
	 * @author 刘中华
	 * @param request
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/toAddClassView")
	public ModelAndView toAddClassView(HttpServletRequest request) throws Exception {
		Collection<SysLookupSimpleVo> lanTopArchiveTypeList = upLoader.getLookUpListByType("LANTOP_ARCHIVE_TYPE");
		String id = request.getParameter("id");
		String dialogId = request.getParameter("dialogId");
		ModelAndView mav = new ModelAndView();
		LantopArchiveClassT lantopArchiveClass = lantopArchiveClassService.getLantopArchiveClassById(id);
		mav.addObject("lantopArchiveClass", lantopArchiveClass);
		lanTopArchiveTypeList = upLoader.getLookUpListByType("LANTOP_ARCHIVE_TYPE");
		mav.addObject("lanTopArchiveTypeList", lanTopArchiveTypeList);
		mav.addObject("dialogId", dialogId);
		mav.setViewName("avicit/im/lantop/basic/libstructuredefine/LantopArchiveClassAdd");
		return mav;
	}

	/**
	 * FIXME (转向属性页面的准备工作)
	 *
	 * @author 刘中华
	 * @param request
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/toAttributeView")
	public ModelAndView toAttributeView(HttpServletRequest request) throws Exception {
		Collection<SysLookupSimpleVo> lanTopArchiveTypeList = upLoader.getLookUpListByType("LANTOP_ARCHIVE_TYPE");
		String id = ServletRequestUtils.getStringParameter(request,"id","");
		String dialogId = ServletRequestUtils.getStringParameter(request,"dialogId","");
		String nodeType = ServletRequestUtils.getStringParameter(request,"nodeType","");
		ModelAndView mav = new ModelAndView();
		LantopArchiveClassT lantopArchiveClass = lantopArchiveClassService.getLantopArchiveClassById(id);
		mav.addObject("lantopArchiveClass", lantopArchiveClass);
		lanTopArchiveTypeList = upLoader.getLookUpListByType("LANTOP_ARCHIVE_TYPE");
		mav.addObject("lanTopArchiveTypeList", lanTopArchiveTypeList);
		mav.addObject("dialogId", dialogId);
		mav.addObject("nodeType", nodeType);
		mav.setViewName("avicit/im/lantop/basic/libstructuredefine/LantopArchiveClassAttribute");
		return mav;
	}

	/**
	 * FIXME (获取标识)
	 *
	 * @author 刘中华
	 * @param request
	 * @param response
	 * @return ModelAndView
	 * @throws
	 */
	@RequestMapping("/getValueByName")
	public Map<String,Object> saveUpdate(HttpServletRequest request, HttpServletResponse response) {

		Map<String,Object> map = new HashMap<>();
		String name = ServletRequestUtils.getStringParameter(request,"name","");
		try {
			String value = Pinyin4jUtil.getPinYinHeadChar(name);
			map.put("value", value);
			map.put("flag", OpResult.success);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("flag", OpResult.failure);
			map.put("msg", "后台处理异常,请联系管理员！");
		}
		return map;
	}

	/**
	 * FIXME (保存添加数据)
	 *
	 * @author 刘中华
	 * @param request
	 * @param response
	 * @return ModelAndView
	 * @throws
	 */
	@RequestMapping("/saveAdd")
	public Map<String,Object> saveAdd(HttpServletRequest request, HttpServletResponse response) {

		Map<String,Object> map = new HashMap<>();
		JSONObject jsonObject = JSONObject.fromObject(request.getParameter("datas"));
		jsonObject.remove("redio");
		jsonObject.remove("selectTemp");

		String names = ServletRequestUtils.getStringParameter(request,"names","");
		String layerType = ServletRequestUtils.getStringParameter(request,"layerType",""); // 两层结构时，0：案卷目录；1：盒目录
		String tempwenIds = ServletRequestUtils.getStringParameter(request,"tempwenIds","");//参考模板文件IDS
		String tempanIds = ServletRequestUtils.getStringParameter(request,"tempanIds","");//参考模板案卷IDS

		LantopArchiveClassT lantopArchiveClass = (LantopArchiveClassT) JSONObject.toBean(jsonObject, LantopArchiveClassT.class);
		// 去掉名称和标识的空格
		String classNodeName = lantopArchiveClass.getArchiveClassNodeName();
		classNodeName = classNodeName.replace(" ", "");
		String classNodeCode = lantopArchiveClass.getArchiveClassNodeCode();
		classNodeCode = classNodeCode.replace(" ", "");
		lantopArchiveClass.setArchiveClassNodeName(classNodeName);
		lantopArchiveClass.setArchiveClassNodeCode(classNodeCode);
		// 插入部门
		String deptId = ThreadContextHelper.getDeptId();
		String orgId = "";
		// 插入组织
		if (null != deptId && !"".equals(deptId)) {
			orgId = lantopArchiveClassService.getOrgIdByDeptId(deptId);
		} else {
			//初始化参数
			deptId = "1";
			orgId = ThreadContextHelper.getOrgId();
		}
		lantopArchiveClass.setDeptId(deptId);
		lantopArchiveClass.setOrgId(orgId);
		try {
			// sysId
			String sysId = "LANTOP";
			// 验证当前组织是否创建全宗信息
			boolean orgCheck = this.lantopArchiveClassService.checkCurrentFonds(orgId, sysId);
			if (orgCheck == false) {
				map.put("flag", OpResult.failure);
				map.put("mes", "请先配置本全宗数据库，再进行库表创建！");
				return map;
			}
			// 验证同级别的节点名称是否已经存在
			boolean ext = lantopArchiveClassService.checkExtName(lantopArchiveClass);
			if (ext) {
				map.put("flag", OpResult.failure);
				if ("10".equals(lantopArchiveClass.getArchiveType())) {
					map.put("mes", "此节点标识已经存在，请修改！");
				} else {
					map.put("mes", "此节点名称已经存在，请修改！");
				}
				return map;
			}
			// 如果类型为"0",清空层级字段
			String archiveType = lantopArchiveClass.getArchiveType();
			if (archiveType.equals("0")) {
				lantopArchiveClass.setTableLayer(null);
			}
			lantopArchiveClass.setSysId(sysId);
			/*// 判断字段中是否存在重复
			Map<String, Object> repeatMap = new HashMap<String, Object>();
			repeatMap.put("ORG_ID", orgId);
			repeatMap.put("SYS_ID", sysId);
			repeatMap.put("MODEL_TYPE", archiveType);
			String repeatString = commTableManagerIntfsService.checkTemplateFieldsRepeat(repeatMap);
			if (!"0".equals(repeatString)) {
				mv.addObject("flag", OpResult.failure);
				mv.addObject("mes", repeatString);
				return mv;
			}*/

			lantopArchiveClass.setNodeSortNumber(BigDecimal.valueOf(1)); // 临时控制
			// 保存对象
			lantopArchiveClassService.insertLantopArchiveClass(lantopArchiveClass);
			// 更新treePath
			String treePath = lantopArchiveClassService.getTreePath(lantopArchiveClass.getId());
			lantopArchiveClass.setArchiveClassNodePath(treePath);
			lantopArchiveClassService.updateLantopArchiveClass(lantopArchiveClass);

			// 调用接口
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("tempwenIds", tempwenIds);//参考模板文件ids
			param.put("tempanIds", tempanIds);//参考模板案卷ids
			param.put("TAB_FLAG", layerType);
			if ("TECH".equals(archiveType)) {
				param.put("isTech", true);
			} else {
				param.put("isTech", false);
			}
			if ("0".equals(archiveType)) {
				param.put("flagAddFiled", "no");
			} else {
				String temp = "12345689TECH"; // 需要去查找的参考模板类型通用代码值
				if (temp.contains(lantopArchiveClass.getArchiveType())) {
					param.put("flagAddFiled", "yes");
					param.put("filedType", lantopArchiveClass.getArchiveType());
				} else {
					param.put("flagAddFiled", "no");
				}
			}
			if ("10".equals(archiveType)) { // 虚拟表
				commTableManagerIntfsService.createCbbTableByIntfs(orgId, deptId, sysId, lantopArchiveClass.getId(), lantopArchiveClass.getArchiveClassNodeName(), lantopArchiveClass.getTableLayer() + "", names, SessionHelper.getLoginSysUserId(request),
						RequestUtil.getClientIp(request), false, lantopArchiveClass.getArchiveClassNodeCode(), param);
			} else {
				if (archiveType.equals("0")) {
					commTableManagerIntfsService.createCbbTableByIntfs(orgId, deptId, sysId, lantopArchiveClass.getId(), lantopArchiveClass.getArchiveClassNodeName(), null, null, SessionHelper.getLoginSysUserId(request), RequestUtil.getClientIp(request), true,
							lantopArchiveClass.getArchiveClassNodeCode(), param);
				} else {
					commTableManagerIntfsService.createCbbTableByIntfs(orgId, deptId, sysId, lantopArchiveClass.getId(), lantopArchiveClass.getArchiveClassNodeName(), lantopArchiveClass.getTableLayer() + "", names, SessionHelper.getLoginSysUserId(request),
							RequestUtil.getClientIp(request), true, lantopArchiveClass.getArchiveClassNodeCode(), param);
				}
			}

			// 回写树节点
			Map<String, Object> nodeMap = new HashMap<String, Object>();
			nodeMap.put("id", lantopArchiveClass.getId());
			nodeMap.put("text", lantopArchiveClass.getArchiveClassNodeName());
			nodeMap.put("parentId", lantopArchiveClass.getParentId());
			List<Map<String, Object>> list = lantopArchiveClassService.getReturnAttribute(lantopArchiveClass.getId());
			nodeMap.put("attributes", list.get(0));
			// 如果为模板库，节点为closed，其他为open
			if (lantopArchiveClass.getTableLayer() != null) {
				nodeMap.put("state", "closed");
			} else {
				nodeMap.put("state", "open");
			}
			map.put("node", nodeMap);
			map.put("flag", OpResult.success);

		} catch (Exception e) {
			e.printStackTrace();
			map.put("flag", OpResult.failure);
			map.put("msg", "后台处理异常,请联系管理员！");
		}
		return map;
	}

	/**
	 * FIXME (保存更新数据)
	 *
	 * @author 刘中华
	 * @param request
	 * @param response
	 * @return ModelAndView
	 * @throws
	 */
	@RequestMapping("/updateSave")
	@SuppressWarnings("unchecked")
	public ModelAndView updateSave(HttpServletRequest request, HttpServletResponse response) {

		ModelAndView mv = new ModelAndView();
		JSONObject jsonObject = JSONObject.fromObject(request.getParameter("datas"));
		jsonObject.remove("redio");
		jsonObject.remove("selectTemp");

		net.sf.json.JSONArray jsonarray = net.sf.json.JSONArray.fromObject(request.getParameter("tabDatas"));
		List<Map<String, Object>> list = (List<Map<String, Object>>) net.sf.json.JSONArray.toCollection(jsonarray, Map.class);

		LantopArchiveClassT lantopArchiveClass = (LantopArchiveClassT) JSONObject.toBean(jsonObject, LantopArchiveClassT.class);
		try {
			// 如果类型为"0",清空层级字段
			String archiveType = lantopArchiveClass.getArchiveType();
			if (archiveType.equals("0")) {
				lantopArchiveClass.setTableLayer(null);
			}
			// 插入部门
			String deptId = ThreadContextHelper.getDeptId();
			String orgId = "";
			if (null != deptId && !"".equals(deptId)) {
				// 插入组织
				orgId = lantopArchiveClassService.getOrgIdByDeptId(deptId);
			} else {
				//初始化参数
				deptId = "1";
				orgId = ThreadContextHelper.getOrgId();
			}
			lantopArchiveClass.setDeptId(deptId);
			lantopArchiveClass.setOrgId(orgId);

			// lantopArchiveClass.setArchiveClassNodeType("-1");// 临时控制

			lantopArchiveClass.setNodeSortNumber(BigDecimal.valueOf(1)); // 临时控制
			// 更新
			lantopArchiveClassService.updateLantopArchiveClass(lantopArchiveClass);
			// 回写树节点

			// 更新表中文名称
			lantopArchiveClassService.updateCbbTablesNameById(list);
			mv.addObject("text", lantopArchiveClass.getArchiveClassNodeName());
			mv.addObject("flag", OpResult.success);

		} catch (Exception e) {
			e.printStackTrace();
			mv.addObject("flag", OpResult.failure);
			mv.addObject("msg", "后台处理异常,请联系管理员！");
		}
		return mv;
	}

	/**
	 * FIXME (删除树节点)
	 *
	 * @author 刘中华
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/deleteSave")
	public Map<String,Object> deleteSave(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String,Object> map = new HashMap<>();
		String nodeId = ServletRequestUtils.getStringParameter(request,"id","");
		String archiveType = ServletRequestUtils.getStringParameter(request,"archiveType","");

		try {
			lantopArchiveClassService.deleteLantopArchiveClassById(nodeId);
			// 部门
			String deptId = ThreadContextHelper.getDeptId();
			// 组织
			String orgId = "";
			if (null != deptId && !"".equals(deptId)) {
				// 插入组织
				orgId = lantopArchiveClassService.getOrgIdByDeptId(deptId);
			} else {
				//初始化参数
				deptId = "1";
				orgId = ThreadContextHelper.getOrgId();
			}
			// sysId
			String sysId = "LANTOP";
			// 删除字段对应设置相关数据
			List<Map<String, Object>> listTab = commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(orgId, deptId, sysId, nodeId, "");// 获取oldTableId
			lantopArchiveClassService.deleteLantopMapSet(listTab);
			// 调用过程，重新生成大视图
			ArrayList<Object> params = new ArrayList<Object>();
			params.add(0, ThreadContextHelper.getOrgId());
			String orgIdentity = SessionHelper.getCurrentOrgIdentity(request);
			SysOrg so = sysOrgAPI.getSysOrgBySysOrgId(orgIdentity);
			String orgCode = so.getOrgCode();
			String tempOrgCode = orgCode;
			if (orgCode.length() > 16) {
				tempOrgCode = orgCode.substring(orgCode.length() - 16);
			}
			params.add(1, tempOrgCode);

			// String status =
			lantopArchiveClassManagerDao.callProcedure("LANTOP_DATA_P.LANTOP_DATA_V", params);
			// 调用接口删除CBB相关数据
			if ("10".equals(archiveType)) {
				commTableManagerIntfsService.deleteCbbTableByNodeIdByIntfs(orgId, deptId, sysId, nodeId, "0");
			} else {
				commTableManagerIntfsService.deleteCbbTableByNodeIdByIntfs(orgId, deptId, sysId, nodeId, "1");
			}
			// 删除文件管理冗余树节点数据
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("FILE_NAME", "个人文件");
			param.put("FILE_CODE", "GRWJ");
			archiveClassManagerIntfsService.deleteRedundancyTreeData(ThreadContextHelper.getOrgId(), ThreadContextHelper.getDeptId(), sysId, param);
			SysLogUtil.log("档案业务模块", "更新档案大视图", OpType.update, OpResult.success, LogBaseFactory.getLogBase());
			map.put("flag", OpResult.success);
		} catch (Exception e) {
			map.put("flag", OpResult.failure);
		}
		return map;
	}

	/**
	 * FIXME (获取模板文件夹下子节点数量)
	 *
	 * @author 刘中华
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/getCountByClassFloder")
	public Map<String,Object> getCountByClassFloder(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		Map<String,Object> map = new HashMap<>();
		try {
			int count = lantopArchiveClassService.getCountByClassFloder(id);
			map.put("count", count);
			map.put("flag", OpResult.success);

		} catch (Exception e) {
			map.put("flag", OpResult.failure);
		}
		return map;
	}

	/**
	 * FIXME (粘贴保存)
	 *
	 * @author 刘中华
	 * @param request
	 * @param response
	 * @return ModelAndView
	 * @throws
	 */
	@RequestMapping("/pasteSave")
	public Map<String,Object> pasteSave(HttpServletRequest request, HttpServletResponse response) {
		String copyId = ServletRequestUtils.getStringParameter(request,"copyId","");
		String inCopyId = ServletRequestUtils.getStringParameter(request,"inCopyId","");
		Map<String,Object> map = new HashMap<>();
		try {
			// 粘贴
			LantopArchiveClassT lantopArchiveClass = lantopArchiveClassService.getLantopArchiveClassById(copyId);
			JSONObject jsonObj = JSONObject.fromObject(lantopArchiveClass);
			jsonObj.remove("createdBy");
			jsonObj.remove("creationDate");
			jsonObj.remove("lastUpdateDate");
			jsonObj.remove("lastUpdateIp");
			jsonObj.remove("lastUpdatedBy");
			jsonObj.remove("version");
			jsonObj.remove("logTitle");
			jsonObj.remove("logType");
			jsonObj.remove("logFormName");
			LantopArchiveClassT lantopArchiveClassNew = (LantopArchiveClassT) JSONObject.toBean(jsonObj, LantopArchiveClassT.class);
			lantopArchiveClassNew.setId("");
			lantopArchiveClassNew.setArchiveClassNodeName(lantopArchiveClass.getArchiveClassNodeName() + "_拷贝");
			lantopArchiveClassNew.setArchiveClassNodeCode(lantopArchiveClass.getArchiveClassNodeCode() + "_COPY");
			lantopArchiveClassNew.setParentId(inCopyId);
			lantopArchiveClassService.insertLantopArchiveClass(lantopArchiveClassNew);
			// 更新treePath
			String treePath = lantopArchiveClassService.getTreePath(lantopArchiveClassNew.getId());
			lantopArchiveClassNew.setArchiveClassNodePath(treePath);
			lantopArchiveClassService.updateLantopArchiveClass(lantopArchiveClassNew);
			// 粘贴成功后,节点id
			String newCopyId = lantopArchiveClassNew.getId();
			// 部门
			String deptId = ThreadContextHelper.getDeptId();
			// 组织
			String orgId = "";
			if (null != deptId && !"".equals(deptId)) {
				// 插入组织
				orgId = lantopArchiveClassService.getOrgIdByDeptId(deptId);
			} else {
				//初始化参数
				deptId = "1";
				orgId = ThreadContextHelper.getOrgId();
			}
			// sysId
			String sysId = "LANTOP";
			boolean isTrue = false;
			if ("10".equals(lantopArchiveClass.getArchiveType())) { // 虚拟表
				isTrue = false;
			} else { // 真实表
				isTrue = true;
			}
			// 获取源表结构标识（案卷级还是盒级）
			// 粘贴调用接口
			commTableManagerIntfsService.copyCbbTableByNodeIdByIntfs(orgId, deptId, sysId, copyId, newCopyId, SessionHelper.getLoginSysUserId(request), RequestUtil.getClientIp(request), isTrue);
			// 回写树节点
			Map<String, Object> nodeMap = new HashMap<String, Object>();
			nodeMap.put("id", lantopArchiveClassNew.getId());
			nodeMap.put("text", lantopArchiveClassNew.getArchiveClassNodeName());
			nodeMap.put("parentId", lantopArchiveClassNew.getParentId());
			List<Map<String, Object>> list = lantopArchiveClassService.getReturnAttribute(lantopArchiveClass.getId());
			nodeMap.put("attributes", list.get(0));
			nodeMap.put("state", "closed");
			map.put("node", nodeMap);
			map.put("flag", OpResult.success);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("flag", OpResult.failure);
			map.put("msg", "后台处理异常,请联系管理员！");
		}
		return map;
	}

	/**
	 * FIXME (转向模板库属性页面的准备工作)
	 *
	 * @author 刘中华
	 * @param request
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/toAttributeTableView")
	public ModelAndView toAttributeTableView(HttpServletRequest request) throws Exception {
		Collection<SysLookupSimpleVo> lanTopArchiveTypeList = upLoader.getLookUpListByType("LANTOP_ARCHIVE_TYPE");
		String id = ServletRequestUtils.getStringParameter(request,"id","");
		String dialogId = ServletRequestUtils.getStringParameter(request,"dialogId","");
		String nodeType = ServletRequestUtils.getStringParameter(request,"nodeType","");
		ModelAndView mav = new ModelAndView();
		LantopArchiveClassT lantopArchiveClass = lantopArchiveClassService.getLantopArchiveClassById(id);
		mav.addObject("lantopArchiveClass", lantopArchiveClass);
		lanTopArchiveTypeList = upLoader.getLookUpListByType("LANTOP_ARCHIVE_TYPE");
		mav.addObject("lanTopArchiveTypeList", lanTopArchiveTypeList);
		mav.addObject("dialogId", dialogId);
		mav.addObject("nodeType", nodeType);
		mav.setViewName("avicit/im/lantop/basic/libstructuredefine/LantopArchiveClassAttributeTable");
		return mav;
	}

	/**
	 * FIXME (加载datagrid)
	 *
	 * @author 刘中华
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 *             ModelAndView
	 * @throws
	 */
	@RequestMapping("/loaddata")
	public ModelAndView doLoadData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView("");
		String nodeId = request.getParameter("id");
		// 部门
		String deptId = ThreadContextHelper.getDeptId();
		// 组织
		String orgId = "";
		if (null != deptId && !"".equals(deptId)) {
			// 插入组织
			orgId = lantopArchiveClassService.getOrgIdByDeptId(deptId);
		} else {
			//初始化参数
			deptId = "1";
			ThreadContextHelper.getOrgId();
			orgId = ThreadContextHelper.getOrgId();
		}
		// sysId
		String sysId = "LANTOP";
		// 调用接口获取库表数据
		List<Map<String, Object>> list = commTableManagerIntfsService.getCbbTableInfoByNodeIdByIntfs(orgId, deptId, sysId, nodeId, "");
		mav.addObject("rows", list);
		mav.setView(null);
		return mav;
	}

	/**
	 * 此方法描述的是:分类树加载
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author zhuf
	 * @createDate 2014-8-21
	 * @version 1.0
	 */
	@RequestMapping("/findChildsNode")
	public ModelAndView findChildsNode(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView();
		List<TreeNode> nodes = new ArrayList<TreeNode>();
		String currOrg = ThreadContextHelper.getOrgId();// 获取当前用户组织ID
		try {
			int level = 1;
			// 默认为根节点
			if (StringUtils.isEmpty(id)) {
				id = "ROOT";
			}
			if ("ROOT".equals(id)) {
				level = 2;
			}
			nodes = this.lantopArchiveClassService.getCommTempletInfoTreeNodes(id, level, currOrg);
			mv.addObject("result", OpResult.success.ordinal());
		} catch (Exception e) {
			mv.addObject("result", OpResult.failure.ordinal());
			mv.addObject("msg", "后台处理异常，" + e.getMessage());
		}
		mv.addObject("data", nodes);
		return mv;
	}

	/***
	 * 根据节点ID查找节点archiveType
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getParentTypeById")
	public ModelAndView getParentTypeById(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView();
		String pid = request.getParameter("pid");
		String archiveType = lantopArchiveClassService.getParentTypeById(pid);
		mav.addObject("archiveType", archiveType);
		mav.setView(null);
		return mav;
	}

	@RequestMapping("/getCurrentOrgId")
	@ResponseBody
	public String getCurrentOrg(HttpServletRequest request){
		return SessionHelper.getCurrentOrgIdentity();
	}

	@RequestMapping("/syncToSubOrg")
	@ResponseBody
	public Map<String,Object> syncToSubOrg(HttpServletRequest request, String nodeId){
		Map<String,Object> result = new HashMap<>();
		try{
			String orgId = ThreadContextHelper.getOrgId();
			List<SysOrg> subOrgs = sysOrgAPI.getAllSubSysOrgListBySysOrgId(orgId);
			lantopArchiveClassService2.syncToSubOrg(orgId, subOrgs, nodeId);
			result.put("flag", OpResult.success);
		}catch (Exception e){
			e.printStackTrace();
			result.put("flag", OpResult.failure);
		}
		return result;
	}

	@RequestMapping("/doSyncArchiveClassAndTables")
	@ResponseBody
	public Map<String,Object> doSyncArchiveClassAndTables(HttpServletRequest request, String nodeId){
		String orgId = ThreadContextHelper.getOrgId();
		List<SysOrg> subOrgs = sysOrgAPI.getAllSubSysOrgListBySysOrgId(orgId);
		List<String> orgIds = new ArrayList<>(subOrgs.size());
		for (SysOrg subOrg : subOrgs) {
			orgIds.add(subOrg.getId());
		}
		Map<String,Object> result = new HashMap<>();
		try {
			lantopArchiveClassService2.syncCbbTabColumns(nodeId, orgIds);
//			result.put("syncInfo", syncInfo);
			result.put("flag", OpResult.success);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("flag", OpResult.failure);
		}
		return result;
	}
}
